package com.example.auv_660.network.tcp;

import com.example.auv_660.util.FileUtils;
import com.example.auv_660.util.Tools;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

public class ModuleWriteHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel asynchronousSocketChannel;

    public ModuleWriteHandler(AsynchronousSocketChannel asynchronousSocketChannel) {
        this.asynchronousSocketChannel = asynchronousSocketChannel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        if (attachment.hasRemaining()) {
            this.asynchronousSocketChannel.write(attachment, attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        exc.printStackTrace();
    }

    public void sendCommandToModule(String command) {
        //System.out.println("send command: " + command);

        FileUtils.INSTANCE.getFileWrite().writeCMD(Tools.DateFormat(new Date(), "S") + "," + command + "\n");

        if (command != null && this.asynchronousSocketChannel != null) {
            byte[] bytes = command.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();

            try {
                String IP = this.asynchronousSocketChannel.getRemoteAddress().toString();
            } catch (IOException e) {

                e.printStackTrace();
            }
            this.asynchronousSocketChannel.write(writeBuffer, writeBuffer, this);
        }
    }
}
